package me.opbukkitdemo.fabric.mixin;

import com.mojang.authlib.GameProfile;
import me.opbukkitdemo.common.event.PlayerOpChangeEvent;
import net.minecraft.server.PlayerManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

import java.util.UUID;

/**
 * @author langle__
 * @version 1.0
 */
@Mixin(PlayerManager.class)
public abstract class PlayerManagerMixin {

    @Shadow public abstract boolean isOperator(GameProfile profile);

    @Inject(method = "addToOperators", at = @At("HEAD"), cancellable = true)
    public void addToOperators(GameProfile profile, CallbackInfo ci) {
        UUID uuid = profile.getId();
        Player player = Bukkit.getPlayer(uuid);
        if (player == null || !player.isOnline()) return;
        PlayerOpChangeEvent event = new PlayerOpChangeEvent(player, isOperator(profile), true);
        Bukkit.getPluginManager().callEvent(event);
        if (event.isCancelled()) {
            ci.cancel();
        }
    }

    @Inject(method = "removeFromOperators", at = @At("HEAD"), cancellable = true)
    public void removeFromOperators(GameProfile profile, CallbackInfo ci) {
        UUID uuid = profile.getId();
        Player player = Bukkit.getPlayer(uuid);
        if (player == null || !player.isOnline()) return;
        PlayerOpChangeEvent event = new PlayerOpChangeEvent(player, isOperator(profile), false);
        Bukkit.getPluginManager().callEvent(event);
        if (event.isCancelled()) {
            ci.cancel();
        }
    }

}
